<template>
  <el-dialog
    ref="refDlg"
    title="新增保证金"
    :visible.sync="dialogShow"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :before-close="clearForm"
    width="800px"
    @close="closeDialog"
  >
    <div>
      <el-form ref="refForm" class="financeForm" :rules="formRules" :model="formData" size="mini" label-width="120px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="变更类型:" prop="changeType">
              <el-select v-model="formData.changeType" placeholder="请选择变更类型" style="width:100%">
                <el-option
                  v-for="item in changeTypeList"
                  :key="item.dictCode"
                  :label="item.dictName"
                  :value="item.dictCode"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="变更项目:" prop="changeItem">
              <el-select v-model="formData.changeItem" placeholder="请选择变更项目" style="width:100%">
                <el-option
                  v-for="item in changeItemList"
                  :key="item.dictCode"
                  :label="item.dictName"
                  :value="item.dictCode"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="变更金额:" size="mini" prop="amount">
              <el-input v-model.number="formData.amount" />
            </el-form-item>
          </el-col>
          <!-- <el-col :span="8">
            <el-form-item label="变更时间:" prop="inputAccountNo">
              <el-date-picker
                v-model="formData.deliveryTime"
                size="mini"
                value-format="yyyy-MM-dd HH:mm:ss"
                align="right"
                type="datetime"
                placeholder="选择日期"
                :picker-options="pickerOptions"
              />
            </el-form-item>
          </el-col> -->
          <el-col :span="8">
            <el-form-item label="有无小票:" prop="haveReceipt">
              <el-select v-model="formData.haveReceipt" placeholder="请选择有无小票" style="width:100%">
                <el-option
                  v-for="item in booleansList"
                  :key="item.dictCode"
                  :label="item.dictName"
                  :value="item.dictCode"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="文件编号:" size="mini">
              <el-input v-model="formData.fileCode" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="发函部门:" prop="sendLetterDeptCode">
              <input-with-dialog
                v-model="sendLetterDept"
                :props="{label:'orgName',value:'orgCode'}"
                :multiple="false"
                :focus-query="true"
                :config="sendLetterConfig"
                @change="changeSendLetter"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="发函日期:" prop="sendLetterTime">
              <el-date-picker
                v-model="formData.sendLetterTime"
                size="mini"
                value-format="yyyy-MM-dd HH:mm:ss"
                align="right"
                type="datetime"
                placeholder="选择日期"
                :picker-options="pickerOptions"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="文件摘要:" size="mini">
              <el-input v-model="formData.summary" />
            </el-form-item>
          </el-col>
          <!-- <el-col :span="8">
            <el-form-item label="门店:" prop="customerCode">
              <input-with-dialog
                v-model="shop"
                :props="{label:'name',value:'code'}"
                :multiple="false"
                :focus-query="true"
                :config="shopDialogConfig"
                @change="handleChangeShop"
              />
            </el-form-item>
          </el-col> -->
          <el-col :span="8">
            <el-form-item label="门店建设项目号:" prop="constCode">
              <input-with-dialog
                v-model="constArr"
                :props="{label:'constCode',value:'constCode'}"
                :config="shopDialogConfig"
                @change="constCodeChange"
              />
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item label="说明:" size="mini" prop="remark">
              <el-input v-model="formData.remark" placeholder="请输入说明" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
            <span style="color: #F56C6C; position: absolute; left: 47px; top: 5px;">*</span>
            <el-form-item label="附件上传:" prop="fileList" class="fileMust">
              <div v-for="item in fileTypeList" :key="item.id">
                <div class="qup-title-box">
                  <span class="border" /><span>附件上传-{{ item.attachmentType }}</span>
                </div>
                <file-uploader
                  :data="item.fileList"
                  :file-type="item.fileTypeName"
                  :config-attachment-id="item.id"
                  :limit="20"
                  @remove="removeFile"
                  @upload-success="uploadSuccessFile"
                />
              </div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div slot="footer">
      <el-button size="mini" @click="closeDialog">取消</el-button>
      <el-button size="mini" type="primary" @click="submitForm">保存</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { submitMargin } from '@/api/constructionUnitMng'
// import { getUserInfo } from '@/utils/auth'
// import { getStore } from '@/api/report'
// import { saveFinanceBalance, getFinanceBalance } from '@/api/finance'
// import { getDisCode } from '@/utils/distributor'
import { postConfigAttachmentTemplate } from '@/api/proConfig'
import { getDictByPatchType } from '@/api/dataDict'
import fileUploader from '@/components/importFile'
import { getShopAttachment } from '@/api/decorate'
export default {
  name: 'DemoEditForm',
  components: { fileUploader },
  props: {
    visible: {
      type: Boolean,
      default: false,
      required: true
    },
    detailData: {
      type: [String, Object],
      default: ''
    }
  },
  data() {
    return {
      readonly: false,
      disabled: false,
      dialogVisible: false,
      // storeList: [],
      // customer: [],
      // fileList: [],
      // constArr: [],
      changeTypeList: [],
      changeItemList: [],
      booleansList: [],
      fileTypeList: [],
      formData: {
        recordId: null,
        shopName: '',
        shopCode: '',
        customerName: '',
        customerCode: '',
        mobilePhone: '',
        moneyInit: '',
        moneyPayment: '',
        moneyThis: '',
        remark: '',
        disCode: '',
        deliveryTime: ''
      },
      pickerOptions: {
        disabledDate(time) {
          var date = new Date()
          var y = date.getFullYear()
          var m = date.getMonth() + 1
          var d = date.getDate()
          var nowTime = new Date(`${y}-${m}-${d} 00:00:00`)
          return time.getTime() < nowTime.getTime()
        }
      },
      // 门店
      shopDialogConfig: {
        title: '门店建设号',
        interfacePath: `${process.env.VUE_APP_BASE_API}/api/v1/shopConstruct/page`,
        setting: [
          {
            prop: 'shopCode',
            title: '门店编码'
          },
          {
            prop: 'shopName',
            title: '门店名称'
          },
          {
            prop: 'constCode',
            title: '门店建设号'
          }
        ]
      },
      // 发函部门
      sendLetterConfig: {
        title: '发函部门',
        interfacePath: `${process.env.VUE_APP_BASE_API}/api/v1/remoteUser/organization/domain/marketing/tree/orgType`,
        method: 'get',
        paramField: 'type',
        setting: [
          {
            prop: 'orgCode',
            title: '编码'
          },
          {
            prop: 'orgName',
            title: '名称'
          }
        ],
        // filtersRaw: [{ 'id': 'isSaleOrganization', 'property': 'isSaleOrganization', 'value': '1', 'operator': '=' }],
        pageFlag: true
      },
      formRules: {
        changeType: [
          { required: true, message: '请选择变更类型' }
        ],
        changeItem: [
          { required: true, message: '请选择变更项目' }
          // { pattern: /^[a-z_]+$/, message: '请输入小写字母或下划线' }
        ],
        amount: [
          { required: true, message: '请输入变更金额', trigger: 'blur' }
        ],
        modifName: [
          { required: true, message: '请输入变更金额' }
        ],
        remark: [
          { required: true, message: '请输入说明', trigger: 'blur' }
        ]
      }
    }
  },

  computed: {
    dialogShow: {
      get() {
        return this.visible
      },
      set(val) {
        this.$emit('update:visible', val)
      }
    }
  },
  async created() {
    this.formData.unitCode = this.detailData.unitCode
    // this.formData.id = this.detailData.id
    this.getDictByPatchTypeAll(['CHANGE_TYPE', 'CHANGE_ITEM', 'BOOLEANS']).then(res => {
      this.changeTypeList = res.CHANGE_TYPE
      this.changeItemList = res.CHANGE_ITEM
      this.booleansList = res.BOOLEANS
    })
    postConfigAttachmentTemplate('CONST_UNIT_MARGIN').then(res => {
      if (res.success === 1) {
        // 根据modelId获取每个配置id
        if (res.data && res.data.records) {
          this.fileTypeList = res.data.records
          this.fileTypeList.forEach(row => {
            this.$set(row, 'fileList', [])
          })
        }
      }
    })
  },

  methods: {
    // 获取数据字典
    async getDictByPatchTypeAll(data) {
      const obj = await getDictByPatchType(data)
        .then(res => {
          return res
        })
      return obj
    },

    // 获取附件
    getFiles() {
      getShopAttachment(this.formData.id).then(res => {
        this.fileTypeList.forEach(row => {
          row.fileList = res.data.filter(i => i.configAttachmentId === row.id)
        })
      })
    },
    removeFile() {},
    uploadSuccessFile() {},

    constCodeChange(row) {
      this.formData.constCode = row[0].constCode
    },
    changeSendLetter(row) {
      this.formData.sendLetterDeptCode = row[0].orgCode
      this.formData.sendLetterDeptName = row[0].orgName
    },
    closeDialog() {
      this.dialogShow = false
      this.clearForm()
    },
    clearForm(done) {
      this.formData = {
        recordId: null,
        shopName: '',
        shopCode: '',
        customerName: '',
        customerCode: '',
        mobilePhone: '',
        moneyInit: '',
        moneyPayment: '',
        moneyThis: '',
        remark: '',
        disCode: ''
      }
      this.$refs.refForm && this.$refs.refForm.clearValidate()
      done && done()
    },
    // checkMoney(value) {
    //   const num = value + Number(this.formData.moneyPayment)
    //   if (num > this.formData.moneyInit) {
    //     this.formData.moneyThis = ''
    //     this.$message.warning('本次收款与已收金额之和不可大于期初应收金额')
    //   }
    // },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    // 提交表单处理
    submitForm() {
      if (this.submiting) return
      this.$refs['refForm'].validate((valid) => {
        if (valid) {
          // const obj = {}
          const len = this.fileTypeList.map(item => item.fileList.length)
          // if (this.formData.demandResultHandle === 'ORDER_SUCC') {
          //   if (!len[0]) {
          //     this.$message.warning('请至少上传一个打款凭证附件')
          //     return
          //   }
          // }
          // return
          if (!len[0]) {
            this.$message.warning('请至少上传一个附件')
            return
            // this.formData.attachmentDtos = []
          } else {
            const arr = this.fileTypeList.map(item => item.fileList)
            // return
            this.formData.attachmentDtos = arr.flat()
          }
          // return
          // obj.modelId = this.formData.id
          this.submiting = true
          // changeFileList(this.formData).then(res => {
          //   if (res.success) {
          // this.$message.success('附件上传成功')
          submitMargin(this.formData).then(res => {
            if (res.success) {
              this.$message.success('操作成功')
              this.closeDialog()
              this.$emit('success')
            }
          })
          //   }
          // })
          // saveFinanceBalance(this.formData).then(res => {
          //   this.submiting = false
          //   if (res.success === 1) {
          //     this.$message({
          //       message: '操作成功',
          //       type: 'success'
          //     })
          //     this.closeDialog()
          //     const isNew = !this.formData.id // 是否新增数据 true (新增则刷新列表到第一页)/ false (非新增则刷新当前页)
          //     this.$emit('success', isNew)
          //   }
          // }).catch(() => {
          //   this.submiting = false
          // })
        }
      })
    }
  }
}
</script>
<style lang='scss' scoped>
.img-upload-container {
  width: fit-content;
  display: flex;
  flex-wrap: wrap;
  justify-content: flex-end;
  align-items: center;
  .icon-msg{
    margin-left: 10px;
    color: #999;
  }
}
/deep/.el-date-editor.el-input, .el-date-editor.el-input__inner{
  width: 100%;
}
</style>
